ggplot(rots, aes(day, count, colour = species)) + #looks like species diverge over time
geom_point(alpha = 0.5) +
geom_smooth(se = FALSE) +
scale_y_log10()
ggplot(rots, aes(as.factor(salinity), count)) + #species have similar repsonse to salinity and decrease with increasing salinity
geom_boxplot() +
facet_wrap(~ species) +
scale_y_log10()
ggplot(rots, aes(tp, count)) + #species have similar response to TP and not much difference between TP treatments
geom_boxplot() +
facet_wrap(~ species) +
scale_y_log10()
#try full model first, tp has no effect or interaction
m1 <- lmer(
log_abundance ~ species * log_salinity * tp * day +
(1 | mesocosm),
data = rots
)
summary(m1)
#simplify model with no tp interaction
m2 <- lmer(
log_abundance ~ species * log_salinity * day + tp +
(1 | mesocosm),
data = rots
)
summary(m2)
anova(m1, m2) #m1 is not better than m2 and AIC lower in m2
#tp still doesn't add to model so let's try without tp
m3 <- lmer(
log_abundance ~ species * log_salinity * day +
(1 | mesocosm),
data = rots
)
summary(m3)
anova(m2, m3)
sim <- simulateResiduals(m3)
plot(sim)
m4 <- glmmTMB(
abundance ~ species * log_salinity * day + tp +
(1 | mesocosm),
ziformula = ~1,
family = nbinom2,
data = rots
) #warning because abundance is not non-integer but neg binomial needs integer
summary(m4)
m5 <- glmmTMB(
count ~ species * log_salinity * day + tp +
offset(log(volume_ml)) +
(1 | mesocosm),
family = nbinom2,
data = rots
)
summary(m5)
r2(m5)
res <- simulateResiduals(m5)
plot(res)
testDispersion(res)
testZeroInflation(res)
testUniformity(res)
m5_slope <- glmmTMB(
count ~ species * log_salinity * day + tp +
offset(log(volume_ml)) +
(1 + day | mesocosm),
family = nbinom2,
data = rots)
anova(m5, m5_slope) # basically the same
## add splines so that fit cam be flexible across day
m6 <- glmmTMB(
count ~ species * ns(log_salinity, df = 2) * ns(day, df = 3) + tp +
offset(log(volume_ml)) +
(1 | mesocosm),
family = nbinom2,
data = rots
)
anova(m5, m6)
res6 <- simulateResiduals(m6)
plot(res6)
testZeroInflation(res6)
library(mgcv)
# add smooth for day
m7a <- gam(count ~ species + tp + log_salinity +
s(day, k = 5) + s(mesocosm, bs = "re") + offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7a)
# let day curve dif by species
m7b <- gam(count ~ species + tp + log_salinity +
s(day, by = species, k = 5) + s(mesocosm, bs = "re") +
offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7b)
anova.gam(m7a, m7b, test = "Chisq")
# let salinity be smooth
m7c <- gam(count ~ species + tp +
s(day, by = species, k = 7) + s(mesocosm, bs = "re") +
s(log_salinity, by = species, k = 4) +
offset(log(volume_ml)),
family = nb(), data = rots, method = "REML")
summary(m7c)
anova.gam(m7a, m7b, m7c, test = "Chisq")
gam.check(m7c)
# but actually the pattern over time also varies by salinity
m7d <- gam(
count ~ species + tp +
te(day, log_salinity, by = species, k = c(5, 4)) +
s(mesocosm, bs = "re") +
offset(log(volume_ml)),
family = nb(),
data = rots,
method = "REML"
)
anova.gam(m7c, m7d, test = "Chisq")
gam.check(m7d)
summary(m7d)
res7d <- simulateResiduals(m7d)
plot(res7d)
testZeroInflation(res7d)
testDispersion(res7d)
plotResiduals(res7d, form = rots$day)
plotResiduals(res7d, form = rots$species)
### 3. plot predicted data ###
newdat <- expand.grid(
log_salinity = seq(min(rots$log_salinity), max(rots$log_salinity), length.out = 100),
species = levels(rots$species),
tp = "L",
day = c(7, 21, 35),
volume_ml = mean(rots$volume_ml)
)
newdat$mesocosm <- factor(rots$mesocosm[1], levels = levels(rots$mesocosm))
newdat$salinity <- exp(newdat$log_salinity)
# predict
pred <- predict(m7d, newdata = newdat, type = "link", se.fit = T, exclude = "s(mescosm)")
newdat$pred <- exp(pred$fit) +1
newdat$lwr <- exp(pred$fit - 1.96 * pred$se.fit) + 1
newdat$upr <- exp(pred$fit + 1.96 * pred$se.fit) + 1
# Select only 3 representative days for predictions
pred_lines <- newdat %>% filter(day %in% c(7, 21, 35))
pred_lines$day_linetype <- factor(pred_lines$day, levels = c(7, 21, 35),
labels = c("Day 7", "Day 21", "Day 35"))
# plot raw data points and add 3 predicted lines for 3 representative days
ggplot() +
geom_jitter(data = rots, aes(x = log_salinity, y = abundance+1, color = day),
width = 0.2, alpha = 1, size = 2) +
geom_line(data = pred_lines, aes(x = log_salinity, y = pred,
linetype = day_linetype, color = day), size = 2) +
geom_ribbon(data = pred_lines, aes(x = log_salinity, ymin = lwr, ymax = upr,
fill = day_linetype, group = day_linetype), alpha = 0.2) +
scale_y_log10() +
scale_x_continuous(breaks = log(c(0.04, 0.2, 1, 5)),
labels = c(0.04, 0.2, 1, 5)) +
scale_color_gradient() +
scale_fill_manual(values = c('#203654', '#43709F', '#6DAEF0')) +
guides(fill = "none") +
facet_wrap(~ species, labeller = labeller(species = c(
"Keratella" = "italic('K. cochlearis')",
"Lepadella" = "italic('L. patella')"),
.default = label_parsed)) +
labs(x = "Salinity (ppt)", y = expression(Rotifers~L^{-1}~"(log scale)"), linetype = '', color = 'Day') +
theme_few(17) +
theme(strip.text = element_text(size = 16),
legend.key.width = unit(2, "line"),
legend.key.size = unit(0.4, "cm"))
sal_vals <- c(0.04, 0.2, 1, 5)
newdat <- expand.grid(
log_salinity = log(sal_vals),
species = levels(rots$species),
tp = "L",
day = seq(min(rots$day), max(rots$day), length.out = 100),
volume_ml = mean(rots$volume_ml))
newdat$mesocosm <- factor(rots$mesocosm[1], levels = levels(rots$mesocosm))
# predict
pred <- predict(m7d, newdata = newdat, type = "link", se.fit = T, exclude = "s(mescosm)")
newdat$pred <- exp(pred$fit)
newdat$pred_plus <- newdat$pred + 1
newdat$lwr <- exp(pred$fit - 1.96 * pred$se.fit)
newdat$upr <- exp(pred$fit + 1.96 * pred$se.fit)
#make four lines for salinity
newdat$salinity_f <- factor(exp(newdat$log_salinity),
levels = sal_vals,
labels = c("0.04", "0.2", "1", "5"))
ggplot() +
geom_jitter(data = rots, aes(x = day, y = abundance, color = as.factor(salinity)),
width = 0.2, alpha = 1, size = 2) +
geom_line(data = newdat, aes(x = day, y = pred,
color = salinity_f, group = salinity_f), size = 2) +
geom_ribbon(data = newdat, aes(x = day, ymin = lwr, ymax = upr, fill = salinity_f, group = salinity_f),
alpha = 0.15) +
scale_y_break(c(400, 1400), scales = 0.1, space = 0.1) +   # break axis
scale_y_continuous(breaks = c(0, 100, 200, 300, 400, 1500),
limits = c(0, 1500)) + # specify ticks manually
scale_color_manual(values = c('black', '#DA3A55', '#50CA3D', '#0889E2')) +
scale_fill_manual(values = c('black', '#DA3A55', '#50CA3D', '#0889E2')) +
guides(fill = "none") +
facet_wrap(~ species, labeller = labeller(species = c(
"Keratella" = "italic('K. cochlearis')",
"Lepadella" = "italic('L. patella')"),
.default = label_parsed)) +
labs(x = "Day", y = expression(Rotifers~L^{-1}~""), color = 'Salinity (ppt)') +
theme_few(17) +
theme(strip.text = element_text(size = 16),
axis.title.x = element_text(hjust = 0.42))
### 2. MICROCOSM ANALYSIS ###
rm(list = ls()) # clean global environment
#load in data
invasion <- read.csv("rotifers_invasion.csv")
# adjust the reference (controls); also treatments as factors
invasion <- invasion %>%
mutate(
treatment = relevel(factor(treatment), ref = 'control'),
tp = relevel(factor(tp), ref = "L"),
salinity = as.numeric(salinity),
mesocosm = as.factor(mesocosm),
microcosm = as.factor(microcosm),
start_vol_ml = as.integer(start_vol_ml),
start_count = as.integer(start_count),
end_vol_ml = as.integer(end_vol_ml),
end_count = as.integer(end_count),
log_salinity = log(salinity)
)
#average number of zeros in the end counts
mean(invasion$end_count == 0, na.rm = TRUE)
micro_df <- invasion %>%
group_by(microcosm, salinity, treatment, tp) %>%
summarise(mean_end = mean(end_density),
mean_start = mean(start_density))
ggplot(micro_df, aes(x = as.factor(salinity), y = mean_end,
fill = treatment)) +
geom_boxplot(alpha = 0.6, outlier.shape = NA, width = 0.7) +
geom_jitter(aes(color = treatment),
position = position_jitterdodge(jitter.width = 0.15, dodge.width = 0.8),
size = 2, alpha = 0.7) +
facet_wrap(~tp) +
labs(title = "",
x = "Salinity (ppt)",
y = expression("Survival rate of " * italic("Lecane sp."))) +
theme_few(15)
boxplot(invasion$end_density ~ invasion$salinity)
boxplot(invasion$end_density ~ invasion$tp)
boxplot(invasion$end_density ~ invasion$treatment)
# Distribution of end counts
hist(invasion$end_count)
mean(invasion$end_count)
var(invasion$end_count)
# Relationship between start and end counts
ggplot(invasion, aes(x=start_count, y=end_count, color=treatment)) +
geom_point() +
geom_smooth(method="loess") +
labs(title="End vs Start Counts")
summary(invasion$start_density)
summary(invasion$end_density)
m1 <- glmmTMB(
end_count ~ log_salinity * treatment * tp +
offset(log(start_count)) + # use counts instead of abundance so model takes integar and then offset with volume to account for different sampling volumes
(1 | mesocosm), # random effect to account for paired microcosms incubated in mesocosms
family = nbinom2,
data = invasion
)
summary(m1)
res <- simulateResiduals(m1)
plot(res)
testDispersion(res)
testZeroInflation(res)
###### testing if any interactions help the model #####
m_no3way <- glmmTMB(
end_count ~ log_salinity * treatment +
log_salinity * tp +
treatment * tp +
offset(log(start_count)) +
(1 | mesocosm),
family = nbinom2,
data = invasion
)
anova(m_no3way, m1)
m_noSalTreat <- glmmTMB(
end_count ~ log_salinity + treatment + tp +
log_salinity:tp + treatment:tp +
offset(log(start_count)) +
(1 | mesocosm),
family = nbinom2,
data = invasion
)
anova(m_noSalTreat, m_no3way)
m_noSalTP <- glmmTMB(
end_count ~ log_salinity + treatment + tp +
log_salinity:treatment + treatment:tp +
offset(log(start_count)) +
(1 | mesocosm),
family = nbinom2,
data = invasion
)
anova(m_noSalTP, m_no3way)
m_noTreatTP <- glmmTMB(
end_count ~ log_salinity + treatment + tp +
log_salinity:treatment + log_salinity:tp +
offset(log(start_count)) +
(1 | mesocosm),
family = nbinom2,
data = invasion
)
anova(m_noTreatTP, m_no3way)
##### final model #####
m_final <- glmmTMB(
end_count ~ log_salinity + treatment + tp +
offset(log(start_count)) +
(1 | mesocosm),
family = nbinom2,
data = invasion
)
summary(m_final)
res <- simulateResiduals(m_final)
plot(res)
testDispersion(res)
testZeroInflation(res)
## drop terms to get LRTs
m_noSal <- glmmTMB(
end_count ~ treatment + tp +
offset(log(start_count)) +
(1 | mesocosm),
family = nbinom2,
data = invasion
)
anova(m_noSal, m_final)
m_noTreat <- glmmTMB(
end_count ~ log_salinity + tp +
offset(log(start_count)) +
(1 | mesocosm),
family = nbinom2,
data = invasion
)
anova(m_noTreat, m_final)
m_noTP <- glmmTMB(
end_count ~ log_salinity + treatment +
offset(log(start_count)) +
(1 | mesocosm),
family = nbinom2,
data = invasion
)
anova(m_noTP, m_final)
r2(m_final)
### make new dataframe for predicted values
newdat <- expand.grid(
log_salinity = seq(min(invasion$log_salinity), max(invasion$log_salinity), length.out = 100),
treatment = levels(invasion$treatment),
tp = levels(invasion$tp)[1],   # reference TP
mesocosm = NA,
start_count = 1
)
preds <- predict(m_final, newdata = newdat, type = 'link', re.form = NA, se.fit = TRUE)
newdat$fit <- preds$fit
newdat$se  <- preds$se.fit
# 95% CI
newdat$pred <- exp(newdat$fit)
newdat$lwr  <- exp(newdat$fit - 1.96 * newdat$se)
newdat$upr  <- exp(newdat$fit + 1.96 * newdat$se)
library(scales)
#plot the raw data and predicted values
ggplot() +
geom_jitter(data = invasion, aes(x = log_salinity, y = (end_density/start_density),
shape = treatment, color = treatment), width = 0.15, size = 2) +
geom_ribbon(data = newdat, aes(x = log_salinity, ymin = lwr, ymax = upr, fill = treatment, group = treatment),
alpha = 0.2, color = NA) +
geom_line(data = newdat, aes(x = log_salinity, y = pred, color = treatment), size = 2) +
scale_y_log10(trans = pseudo_log_trans(sigma = 0.1),
breaks = c(0.1, 1, 10)) +
scale_x_continuous(breaks = log(c(0.04, 0.2, 1, 5)),
labels = c(0.04, 0.2, 1, 5)) +
guides(color = guide_legend(title = "Treatment",
override.aes = list(shape = 16)),
fill = "none", shape = "none") +
scale_color_manual(values = c("control" = "#5A96C2", "P. parvum" = "#F1AF40"),
labels = c("control" = "Control", "P. parvum" = expression(italic("P. parvum")))) +
scale_shape_manual(values = c("control" = 16, "P. parvum" = 17),
labels = c("control" = "Control", "P. parvum" = expression(italic("P. parvum")))) +
labs(x = "Salinity (ppt)",
y = expression(italic("L. patella") ~ "L"^{-1}*" (log scale)"),
shape = 'Treatment',
color = 'Treatment') +
theme_few(15)
rm(list = ls()) # clean global environment
#load in data
prym <- read.csv("prymnesin_detection.csv")
prym <- prym %>%
mutate(treatment = as.factor(treatment))
prym$Compound_name <- factor(
prym$Compound_name,
levels = c("PRM-B (1 Cl)", "PRM-B (1 Cl) + hexose Isomer 1", "PRM-B (1 Cl) + hexose Isomer 2", "PRM-B (1 Cl) + 2 hexose")
)
## plot relative prymnesin content detected in dialysis bags
ggplot(data = prym, aes(x = treatment, y = Area, fill = Compound_name)) +
geom_bar(stat = 'identity', position = 'stack') +
scale_fill_viridis_d(option = "D") +
scale_x_discrete(labels = function(x) {
x <- gsub(", Bag \\d+", "", x)   # remove ", Bag 01"
gsub(", ", "\n", x)              # then split onto new lines
}) +
labs(
x = "Treatment",
y = "Area",
fill = "Compound") +
theme_few(15) +
theme(legend.position = c(0.75,0.85),
legend.title = element_blank(),
axis.title.x = element_text(margin = margin(t = 15)))
### 4. MORTALITY BIOASSAY ###
rm(list = ls()) # clean global environment
#load in data
wells <- read.csv("well_plate.csv")
# Convert data types
wells <- wells %>%
mutate(plate = as.factor(plate),
tp = relevel(factor(tp), ref = "L"),
salinity = as.numeric(salinity),
mesocosm = as.factor(mesocosm),
microcosm = as.factor(microcosm),
survival = as.integer(survival),
pparvum = as.factor(pparvum),
log_salinity = log(salinity))
# visualize data
micro_df <- wells %>%
group_by(microcosm, salinity, tp, pparvum) %>%
summarise(survival_rate = mean(survival))
ggplot(micro_df, aes(x = salinity, y = survival_rate,
color = pparvum)) +
geom_jitter(size = 2, alpha = 0.7) +
scale_y_continuous(labels = percent_format(accuracy = 1)) +
facet_wrap(~ tp, labeller = labeller(tp = c("H" = "High Total Phosphorus", "L" = "Low Total Phosphorus"))) +
labs(title = "",
x = "Salinity (ppt)",
y = expression("Survival rate of " * italic("K. cochlearis"))) +
theme_few(15)
# starting with full model
m1 <- glmmTMB(
survival ~ log_salinity * pparvum + tp +
(1 | mesocosm/microcosm),
family = binomial,
data = wells
)
summary(m1)
r2(m1)
res <- simulateResiduals(m1)
plot(res)
testDispersion(res)
testZeroInflation(res)
testUniformity(res)
#drop interaction
m_noInt <- glmmTMB(
survival ~ log_salinity + pparvum + tp +
(1 | mesocosm/microcosm),
family = binomial,
data = wells)
anova(m_noInt, m1)
#drop salinity
m_noSal <- glmmTMB(
survival ~ pparvum + tp +
(1 | mesocosm/microcosm),
family = binomial,
data = wells)
anova(m_noSal, m1)
#drop pparvum
m_noP <- glmmTMB(
survival ~ log_salinity + tp +
(1 | mesocosm/microcosm),
family = binomial,
data = wells)
anova(m_noP, m1)
#drop TP
m_noTP <- glmmTMB(
survival ~ log_salinity * pparvum +
(1 | mesocosm/microcosm),
family = binomial,
data = wells)
anova(m_noTP, m1)
# plot the data with predicted fit
newdat <- expand.grid(
log_salinity = seq(min(wells$log_salinity), max(wells$log_salinity), length.out = 100),
tp       = 'H',
pparvum  = levels(wells$pparvum),
mesocosm = levels(wells$mesocosm)[1],
microcosm = levels(wells$microcosm[1])
)
# predict
newdat$pred <- predict(m1, newdata = newdat, type = "link", re.form = NA)
preds <- predict(m1, newdata = newdat, type = "link", se.fit = TRUE, re.form = NA)
# link scale
newdat$pred_link <- preds$fit
newdat$se_link <- preds$se.fit
# 95% CI on link scale
newdat$lwr_link <- newdat$pred_link - 1.96 * newdat$se_link
newdat$upr_link <- newdat$pred_link + 1.96 * newdat$se_link
# back-transform to response scale
newdat$pred <- plogis(newdat$pred_link)
newdat$lwr <- plogis(newdat$lwr_link)
newdat$upr <- plogis(newdat$upr_link)
ggplot() +
geom_jitter(data = wells, aes(x = log_salinity, y = survival, shape = pparvum, color = pparvum),
width = 0.15, height = 0.08, alpha = 1, size = 2) +
geom_ribbon(data = newdat, aes(x = log_salinity, ymin = lwr, ymax = upr, fill = pparvum, group = pparvum),
alpha = 0.2, color = NA) +
geom_line(data = newdat, aes(x = log_salinity, y = pred, color = pparvum, group = pparvum), size = 2) +
scale_color_manual(values = c("0" = "#5A96C2", "1" = "#F1AF40"),
labels = c("0" = "Control", "1" = expression(italic("P. parvum")))) +
scale_fill_manual(values = c("0" = "#5A96C2", "1" = "#F1AF40"),
labels = c("0" = "Control", "1" = expression(italic("P. parvum")))) +
scale_shape_manual(values = c("0" = 16, "1" = 17),
labels = c("0" = "Control", "1" = expression(italic("P. parvum")))) +
scale_x_continuous(breaks = log(c(0.04, 0.2, 1, 5)),
labels = c(0.04, 0.2, 1, 5)) +
guides(color = guide_legend(override.aes = list(shape = 16)), fill = "none", shape = "none") +
scale_y_continuous(breaks = c(0, 0.2, 0.4, 0.6, 0.8, 1)) +
labs(x = "Salinity (ppt)", y = "Predicted survival probability", color = "Treatment") +
theme_few(15) +
theme(legend.key.width = unit(1.8, "line"),
legend.text = element_text(size=11))
